//
//  DiscoverViewController.m
//  test1
//
//  Created by chen on 16/10/29.
//  Copyright © 2016年 chen. All rights reserved.
//

#import "DiscoverViewController.h"
//#import "HeaderViewDiscover.h"
#import "Masonry.h"
#import "BottomTableViewCell.h"
#import "ButtomTableView.h"
#import "RecommendsModel.h"
#import "MyPushViewController.h"
#import "ModelViewController.h"
#import "ModelViewController2.h"

#define COUNT 3

@interface DiscoverViewController () <UITableViewDelegate,UITableViewDataSource>

//@property(nonatomic,weak)HeaderViewDiscover *headerView;
@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSArray<UIButton *>* arrayBtn;
@property(nonatomic,weak)ButtomTableView *view1;
@property(nonatomic,weak)UIViewController *vc;

@property(nonatomic,assign)NSInteger index;

@property(nonatomic,strong)NSData *data;


//cell数据
@property(nonatomic,strong)NSMutableArray <RecommendsModel *>*arrMDiscover;

@property(nonatomic,assign)int state;

@end

@implementation DiscoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置导航栏
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tabbar_discover"] style:UIBarButtonItemStyleDone target:self action:@selector(presentView2)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"广州" style:UIBarButtonItemStylePlain target:self action:@selector(presentView1)];
    self.navigationItem.title = @"活动行";
    
    //属性初始化
    self.index = 0;
    self.arrMDiscover = [NSMutableArray array];
    self.data = [NSData data];
    
    [self setupUI];
    
    [self loadData];
    
    self.state = 0;
    
    self.tableView.sectionFooterHeight = 2;
    
}

- (void)presentView1 {
    ModelViewController *modelV = [[ModelViewController alloc]init];
    modelV.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:modelV animated:YES completion:nil];
}

- (void)presentView2 {
    ModelViewController2 *modelV = [[ModelViewController2 alloc]init];
    modelV.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:modelV animated:YES completion:nil];
}

- (void)loadData {
    
    NSArray *arrUrlString = @[@"http://api.huodongxing.com/v3/search/query_events?filter=3&date=t8&start=2016-10-30+00%3A00%3A00&end=2016-10-30+23%3A59%3A59&city=&pi=2&ps=20&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?filter=3&date=t8&start=2016-10-30+00%3A00%3A00&end=2016-10-30+23%3A59%3A59&city=&pi=1&ps=20&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?filter=2&city=&pi=1&ps=20&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?filter=3&city=&pi=1&ps=20&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?tag=&city=&pi=1&ps=20&date=&free=&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?tag=&city=&pi=2&ps=20&date=&free=&onlyunexpired=true&onlyunfull=false",
                              @"http://api.huodongxing.com/v3/search/query_events?tag=&city=&pi=3&ps=20&date=&free=&onlyunexpired=true&onlyunfull=false"];
    
    if (_index >= arrUrlString.count) {
        return;
    }
    NSURL *url = [NSURL URLWithString:arrUrlString[_index]];
    //    NSURLSessionDataTask *tast = [NSURLSessionTask ];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _data = [NSData dataWithContentsOfURL:url];
        if (_data ==nil) {
            return ;
        }
    
    //获得json中的词典
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_data options:0 error:nil];
    //获得字典中key为result 的数组
    NSArray *arrResult = dict[@"result"];
    
//    NSMutableArray *arrMDiscover = [NSMutableArray array];
    for (NSDictionary *dict in arrResult) {
        RecommendsModel *model = [RecommendsModel recommendsModelWithDict:dict];
        [_arrMDiscover addObject:model];
    }
    
//    self.arrMDiscover = arrMDiscover.copy;
        
        
        dispatch_async( dispatch_get_main_queue() , ^{
            [self.tableView reloadData];
        });
    });
        
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    float height = scrollView.contentSize.height > _tableView.frame.size.height ? _tableView.frame.size.height : scrollView.contentSize.height ;
//    
//    //向上拉刷新
//    if ((height - scrollView.contentSize.height + scrollView.contentOffset.y)/height >0.2 ) {
//        NSLog(@"向上拉刷新");
//    }
//    //向下拉刷新
//    if (-scrollView.contentOffset.y / _tableView.frame.size.height > 0.2) {
//        NSLog(@"向下拉刷新");
//        [self loadData];
//    }
//    
//}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    
    float height = scrollView.contentSize.height > _tableView.frame.size.height ? _tableView.frame.size.height : scrollView.contentSize.height ;
    
    //向上拉刷新
    if ((height - scrollView.contentSize.height + scrollView.contentOffset.y)/height >0.2 ) {
        _index ++ ;
        [self loadData];
        NSLog(@"向上拉刷新");
    }
    //向下拉刷新
    if (-scrollView.contentOffset.y / _tableView.frame.size.height > 0.2) {
        NSLog(@"向下拉刷新");
        [self loadData];
    }
    
//    NSLog(@"contentinset---%zd",scrollView.contentInset.bottom);
//    if (self.tableView.contentOffset.y < 0) {
//        
//        [self loadData];
//    }
    
//    if (){
//        
////        NSLog(@"%zd",_index);
//        _index ++;
//        [self loadData];
//    }
    
}

- (void)setupUI {
    
    CGFloat widthBtn = self.view.bounds.size.width / COUNT;
    CGSize sizeBtn = CGSizeMake(widthBtn, 30);
    
    //添加三个按钮
    NSMutableArray *arrBtn = [NSMutableArray array];
    for (NSInteger index = 0; index < COUNT; index++) {
        UIButton *button = [[UIButton alloc]init];
        button.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:button];
        [arrBtn addObject:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.view).offset(64);
            make.left.mas_equalTo(self.view).offset(index * widthBtn);
            make.size.mas_equalTo(sizeBtn);
        }];
        NSString *text = index == 0?@"全类型":(index == 1?@"全时段":@"全价位");
        [button setTitle:text forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        //设置tag
        button.tag = index + 1;
        [button addTarget:self action:@selector(clickPresentView:) forControlEvents:UIControlEventTouchUpInside];
    }
    self.arrayBtn = arrBtn;
    
    //底部tabelview
    UITableView *tabV = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:tabV];
    self.tableView = tabV;
    
    [tabV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(94);
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-49);
    }];
    tabV.delegate = self;
    tabV.dataSource = self;
    
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [tabV registerNib:[UINib nibWithNibName:@"BottomTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell4"];
    
//    ButtomTableView *v = [[ButtomTableView alloc]initWithFrame:CGRectZero];
//    v.backgroundColor = [UIColor lightGrayColor];
//    [self.view addSubview:v];
//    [v mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(self.view).offset(94);
//        make.left.right.equalTo(self.view);
//        make.height.mas_equalTo(0);
//    }];
//    self.view1 = v;

    //添加弹出view
    ButtomTableView *v = [[ButtomTableView alloc]initWithFrame:CGRectMake(0, 94, self.view.bounds.size.width, 0) style:UITableViewStylePlain];
    [self.view insertSubview:v aboveSubview:tabV];
//    v.delegate = self;
//    v.dataSource =  self;
    self.view1 = v;
    [v registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellBtn"];
}



- (void)clickPresentView:(UIButton *)sender {
    
    _state = !_state;
    
    CGFloat heightV = sender.tag==1?300:(sender.tag==2?200:100);
    __block CGRect rect = self.view1.frame;
    [UIView animateWithDuration:0.3 animations:^{
        rect.size.height = _state ==1? heightV:0;
        self.view1.frame = rect;
    } completion:^(BOOL finished) {
        [self.view layoutIfNeeded];
    }];
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.state ==1) {
        [self clickPresentView:nil];
    }
    
}


#pragma mark ---数据源、协议
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 5)];
//    
//    return view;
//}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.state ==1) {
        [self clickPresentView:nil];
        
    }
    MyPushViewController *myV = [MyPushViewController new];
    myV.urlString = self.arrMDiscover[indexPath.row].url;
    myV.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:myV animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.state ==1) {
        return 10;
    }
    return self.arrMDiscover.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.state ==1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellBtn" forIndexPath:indexPath];
        cell.textLabel.text = [NSString stringWithFormat:@"--%zd--",indexPath.row];
        return cell;
    }
    
    BottomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
    
    cell.model = self.arrMDiscover[indexPath.row];
    
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
